import { useState, useEffect } from 'react';
import { openDB } from 'idb';

// 初始化数据库
const initDB = async () => {
  return openDB('TodoDB', 1, {
    upgrade(db) {
      db.createObjectStore('todos', { keyPath: 'id', autoIncrement: true });
    },
  });
};

// 数据操作接口
const todoDB = {
  async getAll() {
    const db = await initDB();
    return db.getAll('todos');
  },
  async add(todo) {
    const db = await initDB();
    return db.add('todos', todo);
  },
  async delete(id) {
    const db = await initDB();
    return db.delete('todos', id);
  },
  async update(todo) {
    const db = await initDB();
    return db.put('todos', todo);
  },
};

function App() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');

  // 初次加载读取数据
  useEffect(() => {
    todoDB.getAll().then(setTodos);
  }, []);

  // 添加新待办
  const addTodo = async () => {
    if (!input.trim()) return;
    
    const newTodo = {
      text: input.trim(),
      completed: false,
      createdAt: new Date(),
    };
    
    const id = await todoDB.add(newTodo);
    setTodos([...todos, { ...newTodo, id }]);
    setInput('');
  };

  // 切换完成状态
  const toggleTodo = async (id) => {
    const updated = todos.map(todo => 
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    );
    setTodos(updated);
    await todoDB.update(updated.find(todo => todo.id === id));
  };

  // 删除待办
  const deleteTodo = async (id) => {
    await todoDB.delete(id);
    setTodos(todos.filter(todo => todo.id !== id));
  };

  return (
    <div style={styles.container}>
      <h1 style={styles.title}>Todo List</h1>
      
      <div style={styles.inputContainer}>
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="添加新任务"
          style={styles.input}
          onKeyPress={(e) => e.key === 'Enter' && addTodo()}
        />
        <button onClick={addTodo} style={styles.addButton}>
          ＋
        </button>
      </div>

      <div style={styles.list}>
        {todos.map(todo => (
          <div key={todo.id} style={styles.todoItem}>
            <label style={styles.label}>
              <input
                type="checkbox"
                checked={todo.completed}
                onChange={() => toggleTodo(todo.id)}
                style={styles.checkbox}
              />
              <span style={{...styles.text, ...(todo.completed && styles.completed)}}>
                {todo.text}
              </span>
            </label>
            <button 
              onClick={() => deleteTodo(todo.id)} 
              style={styles.deleteButton}
            >
              ×
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

// 响应式样式
const styles = {
  container: {
    maxWidth: '600px',
    margin: '0 auto',
    padding: '20px',
    fontFamily: 'system-ui, -apple-system, sans-serif',
  },
  title: {
    textAlign: 'center',
    color: '#333',
    fontSize: '2rem',
    marginBottom: '30px',
  },
  inputContainer: {
    display: 'flex',
    gap: '10px',
    marginBottom: '20px',
  },
  input: {
    flex: 1,
    padding: '12px',
    border: '1px solid #ddd',
    borderRadius: '8px',
    fontSize: '16px',
    outline: 'none',
  },
  addButton: {
    padding: '0 20px',
    background: '#4CAF50',
    color: 'white',
    border: 'none',
    borderRadius: '8px',
    fontSize: '24px',
    cursor: 'pointer',
  },
  list: {
    display: 'flex',
    flexDirection: 'column',
    gap: '12px',
  },
  todoItem: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '15px',
    background: '#f8f8f8',
    borderRadius: '8px',
    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
  },
  label: {
    display: 'flex',
    alignItems: 'center',
    gap: '10px',
    flex: 1,
  },
  checkbox: {
    width: '20px',
    height: '20px',
    accentColor: '#4CAF50',
  },
  text: {
    fontSize: '16px',
    color: '#333',
  },
  completed: {
    textDecoration: 'line-through',
    color: '#999',
  },
  deleteButton: {
    background: 'transparent',
    border: 'none',
    color: '#ff4444',
    fontSize: '24px',
    cursor: 'pointer',
    padding: '0 8px',
  },
};

export default App;